﻿using BotDetector.Core.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using TFIDFExample;

namespace BotDetector.Core.SVMModule
{
    public class SvmTrainer
    {
        SvmFileOperator svmFileOperator = new SvmFileOperator();

        public void CreateTrainFile()
        {
            int firstCategoryNumber = 0;

            List<string> documents = svmFileOperator.GetTrainDocuments(ref firstCategoryNumber);
            
            var vectorText = GetVectorText(documents);

            List<string> problemFile = GetProblemFile(vectorText, ref firstCategoryNumber);

            svmFileOperator.WriteProblemFile(problemFile);
            svmFileOperator.SaveTFIDF();
        }

        private string VectorTextToString(string labelValue, List<KeyValuePair<int, double>> vectorText)
        {
            StringBuilder builder = new StringBuilder();
            builder.Append(labelValue);
            builder.Append(" ");

            foreach (var entity in vectorText)
            {
                builder.Append(entity.Key);
                builder.Append(":");
                builder.Append(entity.Value);
                builder.Append(" ");
            }

            return builder.ToString();
        }

        private List<string> GetProblemFile(List<List<KeyValuePair<int, double>>> vectorText, ref int firstCategoryNumber)
        {
            List<string> problemFile = new List<string>();

            string labelValue = "+1";
            
            foreach (var lineVector in vectorText)
            {
                firstCategoryNumber--;
                if (firstCategoryNumber == 0) { labelValue = "-1"; };
                string lineText = VectorTextToString(labelValue, lineVector);
                problemFile.Add(lineText);         
            }

            return problemFile;
        }

        private List<List<KeyValuePair<int, double>>> GetVectorText(List<string> documents)
        {
            List<List<KeyValuePair<int, double>>> vectorText = TFIDF.Transform(documents.ToArray(), 0);
            vectorText = TFIDF.Normalize(vectorText);

            return vectorText;
        }
    }
}
